package org.epidroid.epidroid.androsoul.ui.contactlist.messagequeue;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.epidroid.epidroid.R;
import org.epidroid.epidroid.androsoul.ui.AndroSoulActivity;

import android.util.TypedValue;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.ScaleAnimation;
import android.widget.LinearLayout;
import android.widget.ListView;

public class MessageQueue {

	public static final String ANDROSOUL_AUTHOR = "AndroSoul";

	private List<MessageQueueItem> _list;
	private AndroSoulActivity _context;
	//private TableLayout _table = null;
	private ListView _listView = null;
	private MessageQueueAdapter _adapter = null;

	public List<MessageQueueItem> getList() {
		return _list;
	}

	public MessageQueue(AndroSoulActivity context) {
		_list = Collections.synchronizedList(new ArrayList<MessageQueueItem>());

		_listView = (ListView) context.findViewById(R.id.ListViewMessageQueue);

		_context = context;

		_adapter = new MessageQueueAdapter(context,
				R.layout.androsoul_messagequeue_item, _list);
		_listView.setAdapter(_adapter);
	}

	public Iterator<MessageQueueItem> iterator() {
		return _list.iterator();
	}

	public void clear() {
		synchronized (_list) {
			_list.clear();
		}
		_adapter.notifyDataSetChanged();
	}

	public void add(MessageQueueItem m) {
		boolean wasEmpty = _list.isEmpty();
		synchronized (_list) {
			_list.add(m);
		}

		if (wasEmpty) {
			int value = (int) TypedValue.applyDimension(
					TypedValue.COMPLEX_UNIT_DIP, (float) 25, _context
							.getResources().getDisplayMetrics());
			_listView.setLayoutParams(new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, value));
			ScaleAnimation anim = new ScaleAnimation(1f, 1f, 0.0f, 1f);
			anim.setDuration(500);
			_listView.startAnimation(anim);
		}

		_adapter.notifyDataSetChanged();
		_listView.smoothScrollToPosition(_list.size());
	}

	public void addAndroSoulMessage(String content) {
		add(new MessageQueueItem(ANDROSOUL_AUTHOR, content));
	}

	// Delete all messages from message queue whose
	// author is name
	public void flush(String name) {
		synchronized (_list) {
			for (Iterator<MessageQueueItem> it = _list.iterator(); it.hasNext();) {
				MessageQueueItem item = (MessageQueueItem) it.next();
				if (item.getAuthor().equals(name)) {
					it.remove();
				}
			}
		}
		_adapter.notifyDataSetChanged();

		if (_list.size() == 0) {
			_listView.setLayoutParams(new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, 0));
		}
	}

	public void flushAndroSoulMessages() {
		flush(ANDROSOUL_AUTHOR);
	}
}
